<template>
  <div class="contacts-left">
    <div class="top">
      <div class="title">通讯录</div>
      <div class="search">
        <el-input v-model="searchkey" placeholder="搜索" :prefix-icon="Search" @input="searchFn" clearable />
      </div>
      <div class="tab">
        <div class="tab-cot" :class="tabShowIndex === 1 ? 'active' : ''" @click="changTab(1)">
          <el-icon><SvgIcon name="qunzu" /></el-icon>
          <span>全部</span>
        </div>
        <div class="rd"></div>
        <div class="tab-cot" :class="tabShowIndex === 2 ? 'active' : ''" @click="changTab(2)">
          <el-icon><SvgIcon name="zuzhi" /></el-icon>
          <span>组织</span>
        </div>
      </div>
    </div>
    <div class="bottom">
      <el-scrollbar ref="scrollbarRef">
        <ul class="tab-1" v-show="tabShowIndex === 1">
          <li
            v-for="(item, index) in viewUserList"
            :key="index"
            @click="activeFn(item)"
            :class="`${item.isActive ? 'active' : ''}`"
          >
            <div class="name">
              <span>
                <img :src="urlResource + item.avatarUrl" alt="" />
              </span>
              <span>{{ item.name }}</span>
            </div>
            <div v-if="userId === item.id" class="role">我自己</div>
          </li>
        </ul>
        <div class="tab-2" v-show="tabShowIndex === 2">
          <el-tree
            ref="treeRef"
            :data="viewUserList"
            :props="defaultProps"
            @node-click="handleNodeClick"
            highlight-current
            :filter-node-method="filterNode"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node" v-if="!data.isUser">
                <span>{{ node.label }}</span>
              </span>
              <div class="custom-tree-node-leaf" v-else>
                <span>
                  <img :src="data.url" alt="" />
                </span>
                <span>{{ data.label }}</span>
              </div>
            </template>
          </el-tree>
        </div>
        <el-empty v-if="!viewUserList.length" :image-size="100" />
      </el-scrollbar>
    </div>
  </div>
</template>
<script setup lang="ts" name="Contacts">
import { ref, onMounted, computed, reactive } from "vue";
import { Search } from "@element-plus/icons-vue";
import type { User } from "@/api/interface";
import { useUserStore } from "@/stores/modules/user";
import mittBus from "@/utils/mittBus";
// import pinyin from "pinyin";
// api
import { getListAllUser, getAllUserByDepartmentTree } from "@/api/modules/sys";
// 变量
const userStore = useUserStore();
const userId = computed(() => userStore.userInfo.id);
const urlResource = window?.staticConfig.urlResource;
const userList = ref<User.ResUserList[]>([]);
const viewUserList = ref<User.ResUserList[]>([]);
const searchkey = ref("");
const scrollbarRef = ref<any>(null);
const tabShowIndex = ref(1);
const treeRef = ref<any>(null);
interface Tree {
  label: string;
  level: number;
  isLeaf?: boolean;
  isUser?: boolean;
  children?: Tree[];
}
let dataSource: Tree[] = reactive([
  {
    label: "Level one 1",
    level: 0,
    children: [
      {
        label: "Level two 1-1",
        level: 1,
        children: [
          {
            label: "Level three 1-1-1",
            level: 2,
            isLeaf: true
          }
        ]
      }
    ]
  },
  {
    label: "Level one 2",
    level: 0,
    children: [
      {
        label: "Level two 2-1",
        level: 1,
        children: [
          {
            label: "Level three 2-1-1",
            level: 2,
            isLeaf: true
          }
        ]
      },
      {
        label: "Level two 2-2",
        level: 1,
        children: [
          {
            label: "Level three 2-2-1",
            level: 2,
            isLeaf: true
          }
        ]
      }
    ]
  }
]);
const defaultProps = {
  children: "children",
  label: "label"
};
// 事件
const handleNodeClick = (data: Tree) => {
  if (data.isUser) {
    mittBus.emit("UserIdEmit", data.id);
  }
};
/** 方法 */

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.toLowerCase().includes(value);
};

const changTab = (val: number) => {
  if (val === 1) {
    viewUserList.value = userList.value.map(item => {
      item.isActive = item.id === userId.value;
      return item;
    });
    mittBus.emit("UserIdEmit", userId.value);
  } else {
    viewUserList.value = dataSource;
  }
  tabShowIndex.value = val;
  searchkey.value = "";
  scrollbarRef.value.setScrollTop(0);
};
const activeFn = itm => {
  mittBus.emit("UserIdEmit", itm.id);
  viewUserList.value = viewUserList.value.map(item => {
    item.isActive = item.id === itm.id;
    return item;
  });
};
const searchFn = () => {
  if (tabShowIndex.value === 1) {
    viewUserList.value = userList.value.filter(item => {
      return item.name.toLowerCase().includes(searchkey.value);
    });
    viewUserList.value = viewUserList.value.map(item => {
      item.isActive = item.id === viewUserList.value[0].id;
      return item;
    });
  } else {
    treeRef.value!.filter(searchkey.value);
  }
};
// 获取全部用户
const getListAllUserFn = async () => {
  const { data } = await getListAllUser();
  // 拼音排序 然后我默认第一个
  data.sort((a: any, b: any) => {
    return a.name.localeCompare(b.name, "zh");
  });
  const index = data.findIndex(item => item.id === userId.value);
  const self = data.splice(index, 1);
  data.unshift(self[0]);
  userList.value = data.map(item => {
    item.isActive = item.id === userId.value;
    return item;
  });
  viewUserList.value = userList.value;
};
// 数据转化
const getTransFormData = data => {
  let result = [];
  data.forEach((item, index) => {
    if (item.companyName) {
      const children = getTransFormData(item.userByDepartmentModelList) || [];
      result.push({
        id: index,
        label: item.companyName,
        children,
        isLeaf: children.length
      });
    } else {
      if (item.departmentName) {
        const users =
          (item.userModelList &&
            item.userModelList.map(item => {
              return {
                id: item.userId,
                label: item.userName,
                url: urlResource + item.userAvatarUrl,
                isUser: true
              };
            })) ||
          [];
        const departMent = (item.userByDepartmentModelList && getTransFormData(item.userByDepartmentModelList)) || [];
        const children = [...users, ...departMent];
        result.push({
          id: "1-" + index,
          label: item.departmentName,
          children,
          isLeaf: children.length
        });
      }
    }
  });
  return result;
};
// 查询全部用户_根据组织树状
const getAllUserByDepartmentTreeFn = async () => {
  const { data } = await getAllUserByDepartmentTree();
  // 处理数据
  dataSource = getTransFormData(data);
  // viewUserList.value = dataSource;
};
onMounted(() => {
  getListAllUserFn();
  getAllUserByDepartmentTreeFn();
  mittBus.emit("UserIdEmit", userId.value);
});
</script>
<style lang="scss" scoped>
ul,
li {
  padding: 0;
  margin: 0;
}
.contacts-left {
  display: flex;
  flex-flow: column nowrap;
  user-select: none;
  .title {
    box-sizing: border-box;
    height: 72px;
    padding: 0 30px;
    font-size: 16px;
    line-height: 72px;
    color: #333333;
  }
  .search {
    padding: 0 30px;
    margin-top: 10px;
  }
  .tab {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 56px;
    margin-top: 10px;
    border-bottom: 1px solid #f4f4f4;
    .rd {
      flex: 0 0 1px;
      height: 36px;
      background: #f4f4f4;
    }
    .tab-cot {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      span:last-child {
        margin-left: 10px;
      }
    }
    .active {
      color: var(--el-color-primary);
    }
  }
  .bottom {
    flex: 1;
    height: 0;
    .tab-1 {
      display: flex;
      flex-flow: column nowrap;
      align-items: center;
      width: 100%;
      margin-top: 10px;
      li {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        height: 56px;
        cursor: pointer;
        border-bottom: 1px solid #f4f4f4;
        border-left: 2px solid transparent;
        .name {
          display: flex;
          align-items: center;
          margin-left: 30px;
          span:first-child {
            width: 32px;
            height: 32px;
            img {
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
          span:last-child {
            margin-left: 10px;
            font-size: 14px;
            color: #333333;
          }
        }
        .role {
          margin-right: 20px;
          font-size: 12px;
          color: #999999;
        }
      }
      .active {
        background: var(--el-color-primary-light-9);
        border-left: 2px solid var(--el-color-primary);
      }
    }
    .tab-2 {
      :deep(.el-tree) {
        height: 80%;

        // padding: 0 30px !important;
        overflow: auto;
        .el-tree-node__content {
          box-sizing: border-box;
          height: 56px;
          border-left: 2px solid transparent;
        }
      }
      :deep(.el-tree--highlight-current) {
        .el-tree-node.is-current > .el-tree-node__content {
          background-color: var(--el-fill-color-light);
          .el-tree-node__label,
          .el-tree-node__expand-icon {
            color: #333333;
          }
          .is-leaf {
            color: transparent;
          }
          &:has(.custom-tree-node-leaf) {
            background: var(--el-color-primary-light-9);
            border-left: 2px solid var(--el-color-primary);
          }
        }
      }
      .custom-tree-node {
        font-size: 14px;
        color: #333333;
      }
      .custom-tree-node-leaf {
        display: flex;
        align-items: center;
        span:first-child {
          width: 32px;
          height: 32px;
          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }
        }
        span:last-child {
          margin-left: 10px;
          font-size: 14px;
          color: #333333;
        }
      }
    }
  }
}
</style>
